<template>
  <view
    :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"
    class="canvas-container"
  >
    <canvas
      v-if="show"
      :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"
      id="canvas"
      canvas-id="canvas"
    ></canvas>
  </view>
</template>

<script>
export default {
  name: 'ThAddWater',
  data() {
    return {
      canvasWidth: '',
      canvasHeight: '',
      maxWidth: 1920,
      maxHeight: 1920,
      show: true,
    };
  },
  created() {},
  methods: {
    reset() {
      this.show = false;
      this.$nextTick(() => {
        this.show = true;
      });
    },
    getImageInfo(src) {
      return new Promise((resolve, reject) => {
        uni.getImageInfo({
          src,
          success: (res) => {
            resolve(res);
          },
          fail: (err) => {
            reject(err);
          },
        });
      });
    },
    toBase64(file) {
      // #ifdef H5
      const reader = new FileReader();
      return new Promise((resolve) => {
        reader.onload = function (res) {
          resolve(reader.result);
        };
        if (file) {
          reader.readAsDataURL(file);
        } else {
          throw new Error('没有提供file文件');
        }
      });
      // #endif
    },
    handleDraw(options = {}) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          const ctx = uni.createCanvasContext('canvas', this);
          // const ctx = canvas.getContext("2d");
          const {
            imageResource,
            imageWidth,
            imageHeight,
            waterText,
            waterPaddingX = 40,
            waterPaddingY = 120,
          } = options;
          ctx.drawImage(imageResource, 0, 0, imageWidth, imageHeight);
          // console.log(imageWidth, imageHeight)
          // 绘制水印
          let offsetX = 0;
          let offsetY = 0;
          let fontSize = imageWidth / 5 / waterText.length;
          if (fontSize < 12) {
            fontSize = 12;
          }
          if (fontSize > 28) {
            fontSize = 28;
          }
          ctx.setFontSize(fontSize);
          // console.log(imageWidth, fontSize)
          ctx.setFillStyle('rgba(0, 0, 0, 0.1)');
          const textMetrics = ctx.measureText(waterText);
          const textWidth = textMetrics.width;
          while (true) {
            if (offsetY >= imageHeight) {
              break;
            }
            ctx.translate(offsetX + textWidth / 2, offsetY + fontSize / 2);
            ctx.rotate((-20 * Math.PI) / 180);
            ctx.fillText(waterText, 0 - textWidth / 2, 0 - fontSize / 2);
            ctx.rotate((20 * Math.PI) / 180);
            ctx.translate(0 - (offsetX + textWidth / 2), 0 - (offsetY + fontSize / 2));
            offsetX = offsetX + waterPaddingX + textWidth;
            if (offsetX >= imageWidth) {
              offsetX = waterPaddingX;
              offsetY = offsetY + waterPaddingY + fontSize;
            }
          }
          ctx.translate(imageWidth / 2, imageHeight / 2);
          ctx.rotate((20 * Math.PI) / 180);
          ctx.draw(true, () => {
            console.log('绘制完成');
            uni.canvasToTempFilePath({
              canvasId: 'canvas',
              success(res) {
                console.log('导出成功');
                resolve(res.tempFilePath);
              },
              fail(err) {
                console.log(err);
                reject(err);
              },
            });
          });
        }, 200);
      });
    },
    async startCreate(image) {
      try {
        const imageInfo = await this.getImageInfo(image);
        // console.log(imageInfo)
        let { path: imagePath, width, height, type } = imageInfo;
        if (width > this.maxWidth) {
          width = this.maxWidth;
          height = (width / imageInfo.width) * height;
        }
        if (height > this.maxHeight) {
          const preHeight = height;
          height = this.maxHeight;
          width = (height / preHeight) * width;
        }
        this.canvasWidth = width;
        this.canvasHeight = height;
        const imageBase64 = await this.toBase64(imagePath);
        const res = await this.handleDraw({
          imageResource: imageBase64,
          imageWidth: width,
          imageHeight: height,
          waterText: this.$store.state.info.realName,
          waterPaddingX: 40,
          waterPaddingY: 120,
        });
        // console.log(res)
        // const base64 = await this.toBase64(res)
        return res;
      } catch (error) {
        console.log(error);
        throw new Error(error.message);
      }
    },
  },
};
</script>

<style scoped lang="scss">
.canvas-container {
  position: absolute;
  top: 0;
  transform: translateX(-120%);
  z-index: -1;
}
</style>
